#!/usr/bin/env python
# -*- coding: UTF-8 -*-
# @Project ：project
# @FileName：main.py
# @IDE     ：PyCharm
# @Author  ：叶鸟翼
# @Time    ：2022/10/3 17:06
# @Desc    ：https://unittestreport.readthedocs.io/en/latest/
import os
import time

from unittestreport import TestRunner, Load

from settings import *
from utils.config import rfc
from utils.log import logger

MAIL_CONF = rfc.get_mail_config()
DING_CONF = rfc.get_dingtalk_config()


def auto_clear_resource(path, backup_count):
    """自动清理日志或报告并保留指定的最新份数

    :param path: 文件夹/目录 名称
    :param backup_count: 最新保留份数
    :return:
    """
    files = []
    path = os.path.join(ROOT_PATH, path)
    for file in os.listdir(path):
        files.append(os.path.join(path, file))

    # 按照文件的创建时间降序排序
    files.sort(key=os.path.getctime, reverse=True)

    # 保留最新的backup_count份文件
    for file in files[backup_count:]:
        os.remove(file)


def run(email: bool = False, dingtalk: bool = False, backup_count: int = 5):
    """启动测试

    :param dingtalk: 是否发送钉钉(默认不发送)
    :param email: 是否发送邮件(默认不发送)
    :param backup_count: 最新保留的份数(日志和报告)
    :return:
    """
    logger.info(
        r"""
              _    _         _      _____         _   
   __ _ _ __ (_)  / \  _   _| |_ __|_   _|__  ___| |_ 
  / _` | '_ \| | / _ \| | | | __/ _ \| |/ _ \/ __| __|
 | (_| | |_) | |/ ___ \ |_| | || (_) | |  __/\__ \ |_ 
  \__,_| .__/|_/_/   \_\__,_|\__\___/|_|\___||___/\__|
       |_| 
      Starting      ...     ...     ...     ...     
    """
    )

    # 1.加载用例到测试套件
    suites = Load.discover(TEST_PATH, pattern='test*.py')
    # 自动化测试报告名称
    report_name = time.strftime("%Y%m%d_%H%M%S") + ".html"

    # 2.创建一个用例运行程序
    runner = TestRunner(suites,
                        filename=report_name,
                        report_dir=REPORT_PATH,
                        title='测试报告',
                        tester='叶鸟翼',
                        desc="接口自动化测试报告",
                        templates=2)

    # 3.运行测试用例
    # count:用来指定用例失败重运行的次数
    # interval:指定每次重运行的时间间隔
    runner.run(count=3, interval=3)

    # 4.自动清理过期的日志或报告
    auto_clear_resource(LOG_PATH, backup_count)
    auto_clear_resource(REPORT_PATH, backup_count)

    # 推送测试结果到邮件、钉钉或企业微信
    if email:
        # 发送邮件通知
        runner.send_email(**MAIL_CONF)

    if dingtalk:
        # 发送钉钉通知
        runner.dingtalk_notice(**DING_CONF)


if __name__ == '__main__':
    run()
